/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { http } from '@kit.NetworkKit';

class Http {
  url: string;
  extraData: Object;
  options: http.HttpRequestOptions;

  public executor_backend_url = 'http://10.149.158.72:8082'
  public model_backend_url = 'http://10.149.158.72:8081'
  public opcua_backend_url = 'http://10.149.158.72:8080'

  constructor() {
    this.url = '';
    this.options = {
      method: http.RequestMethod.GET,
      extraData: this.extraData,
      header: { 'Content-Type': 'application/json' },
      readTimeout: 50000,
      connectTimeout: 50000
    };
  };

  setUrl(url: string) {
    this.url = url;
  }

  setMethod(method: string) {
    switch (method) {
      case 'GET':
        this.options.method = http.RequestMethod.GET;
        break;
      case 'HEAD':
        this.options.method = http.RequestMethod.HEAD;
        break;
      case 'OPTIONS':
        this.options.method = http.RequestMethod.OPTIONS;
        break;
      case 'TRACE':
        this.options.method = http.RequestMethod.TRACE;
        break;
      case 'DELETE':
        this.options.method = http.RequestMethod.DELETE;
        break;
      case 'POST':
        this.options.method = http.RequestMethod.POST;
        break;
      case 'PUT':
        this.options.method = http.RequestMethod.PUT;
        break;
      case 'CONNECT':
        this.options.method = http.RequestMethod.CONNECT;
        break;
      default:
        this.options.method = http.RequestMethod.GET;
        break;
    }
  }

  setExtraData(extraData: Object) {
    this.options.extraData = extraData;
  }

  setOptions(option: Object) {
    this.options = option;
  }

  setList(list: number[], flag: number) {
    list = [];
    for (let i = 0; i < flag; i++) {
      list[i] = i;
    }
    return list;
  }

  setParameter(keys: string[], values: string[]) {
    let result = {};
    for (let i = 0; i <= keys.length - 1; i++) {
      let key = keys[i];
      let value = values[i];
      result[key] = value;
    }
    return result;
  }

  // 包装同步，等待Promise对象。返回Promise的value结果(一般是object)
  async request() {
    try {
      let result = 'async not return'
      await this.requestAsync().then(value => {
        result = String(value)
        console.log("promise Resolve 结果:", value); // 输出：Resolve 结果: 成功的数据
      }).catch(error => {
        result = String(error)
        console.log("promise Reject 原因:"+ error?.code + error?.message); // 输出：Reject 原因: 失败的原因
      });
      return result;
    } catch (error) {
      console.error("request failed:", error);
      throw error; // 抛出原始错误对象，而非字符串
    }
  }

  // 将回调函数包装为 Promise，返回Promise
  requestAsync() {
    return new Promise((resolve, reject) => {
      let httpRequest = http.createHttp();
      httpRequest.request(this.url, this.options, (err, data) => {
        if (!err) {
          const result = data.result.toString();
          AppStorage.setOrCreate('requestResult', result);
          console.info("requestAsync SUCCESS: " + result);
          resolve(result); // 成功时传递结果
        } else {
          console.error(`requestAsync ERROR code=${err?.code} message=${err?.message}`)
          httpRequest.destroy();
          reject(err || data); // 失败时传递错误
        }
        httpRequest.destroy(); // 统一释放资源
      });
    });
  }

  // 包装Restful-query/path，返回Promise的value结果(一般是object)
  requestRestful(url: string, path:string, method: string, urlKeys: string[], urlValues: string[]){
    let total_url = url + path
    if(urlKeys.length > 0) total_url += '?'

    for (let i = 0; i <= urlKeys.length - 1; i++) {
      let key = urlKeys[i];
      let value = urlValues[i];
      total_url += key + '=' + value
      if(i != urlKeys.length - 1) total_url+= '&'
    }
    this.setUrl(total_url);
    this.setMethod(method);
    this.setExtraData({});
    return this.request()
  }

  // 包装Restful-jsonBody，返回Promise的value结果(一般是object)
  requestRestfulWithBody(url: string, path:string, method: string, extraData: Object){
    let total_url = url + path

    this.setUrl(total_url);
    this.setMethod(method);
    this.setExtraData(extraData);
    return this.request()
  }

}

export default new Http();